package com.example.demo.service.impl;

import com.example.demo.dao.IOrderInfoRepository;
import com.example.demo.dao.IOrderRefundRepository;
import com.example.demo.entity.OrderInfo;
import com.example.demo.entity.OrderRefund;
import com.example.demo.service.IOrderRefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 退款服务实现类
 * Created by Hy on 2018/8/21.
 */
@Service
public class OrderRefundService implements IOrderRefundService{
    @Autowired
    private IOrderRefundRepository iOrderRefundRepository;
    @Autowired
    private IOrderInfoRepository infoRepository;

    @Override
    public OrderRefund createRefund(String refundId, String reason, float money, Map<String, String> map) {
        //退款账户
        String buyerLogonId = map.get("buyer_logon_id");
        //已退款总金额
        float refundFee = Float.parseFloat(map.get("refund_fee"));
        //退款订单号
        String outTradeNo = map.get("out_trade_no");
        //退款时间
        String gmtRefundPay = map.get("gmt_refund_pay");

        OrderRefund orderRefund = new OrderRefund(refundId,outTradeNo,money,buyerLogonId,reason,gmtRefundPay);

        //1.添加退款记录
        iOrderRefundRepository.saveAndFlush(orderRefund);

        //2.更新总计退款金额
        OrderInfo orderInfo = infoRepository.findByOrderId(outTradeNo);
        orderInfo.setRefundMoney(refundFee);
        //如果金额全部退完，修改订单状态为TRADE_CLOSED
        if(refundFee == orderInfo.getMoney()){
            orderInfo.setStatus("TRADE_CLOSED");
        }
        infoRepository.saveAndFlush(orderInfo);
        return orderRefund;
    }

    @Override
    public List<OrderRefund> listRefund(String orderId, String refundId) {
        List<OrderRefund> list = iOrderRefundRepository.findByOrderIdOrRefundId(orderId, refundId);
        return list;
    }
}
